package com.iddactylogram.common.core;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public final class SeqInstance {
    private final static Object APP_CREATE_NAME_LOCK = new Object();
    //初始时间（2022-01-01 00:00:00）
    private final static long TWEPOCH = 1640966400000L;
    private final static ConcurrentMap<String, SeqInstance> CONCURRENT_MAP = new ConcurrentHashMap<>();
    private final String appName;
    private long lastCurrTimeMs;
    private long count = 0;

    private SeqInstance(String appName) {
        this.appName = appName;
    }

    public static SeqInstance getInstance(String appName) {
        SeqInstance seqInstance = CONCURRENT_MAP.get(appName);
        if (seqInstance == null) {
            synchronized (APP_CREATE_NAME_LOCK) {
                seqInstance = CONCURRENT_MAP.get(appName);
                if (seqInstance == null) {
                    seqInstance = new SeqInstance(appName);
                    CONCURRENT_MAP.put(appName, seqInstance);
                }
            }
        }
        return seqInstance;
    }

    public synchronized long genId() {
        long currTimes = System.currentTimeMillis();
        //当前时间比上次生成的时间大，更新时间，count置为0
        if (currTimes > lastCurrTimeMs) {
            lastCurrTimeMs = currTimes;
            count = 0;
        } else {
            count++;
        }
        long diffMs = currTimes - TWEPOCH;
        return diffMs << 16 | count;
    }

    public String getAppName() {
        return appName;
    }
}
